package com.example.weather;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 古嘉华 on 2018/4/26.
 */


public class GzFragment extends android.support.v4.app.Fragment {
/*    private final String weatherJson = "{\n" +
            "    \"status\": 200,\n" +
            "    \"data\": {\n" +
            "        \"wendu\": \"29\",\n" +
            "        \"ganmao\": \"各项气象条件适宜，发生感冒机率较低。但请避免长期处于空调房间中，以防感冒。\",\n" +
            "        \"forecast\": [\n" +
            "            {\n" +
            "                \"fengxiang\": \"南风\",\n" +
            "                \"fengli\": \"3-4级\",\n" +
            "                \"high\": \"高温 32℃\",\n" +
            "                \"type\": \"多云\",\n" +
            "                \"low\": \"低温 17℃\",\n" +
            "                \"date\": \"16日星期二\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"fengxiang\": \"南风\",\n" +
            "                \"fengli\": \"微风级\",\n" +
            "                \"high\": \"高温 34℃\",\n" +
            "                \"type\": \"晴\",\n" +
            "                \"low\": \"低温 19℃\",\n" +
            "                \"date\": \"17日星期三\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"fengxiang\": \"南风\",\n" +
            "                \"fengli\": \"微风级\",\n" +
            "                \"high\": \"高温 35℃\",\n" +
            "                \"type\": \"晴\",\n" +
            "                \"low\": \"低温 22℃\",\n" +
            "                \"date\": \"18日星期四\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"fengxiang\": \"南风\",\n" +
            "                \"fengli\": \"微风级\",\n" +
            "                \"high\": \"高温 35℃\",\n" +
            "                \"type\": \"多云\",\n" +
            "                \"low\": \"低温 22℃\",\n" +
            "                \"date\": \"19日星期五\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"fengxiang\": \"南风\",\n" +
            "                \"fengli\": \"3-4级\",\n" +
            "                \"high\": \"高温 34℃\",\n" +
            "                \"type\": \"晴\",\n" +
            "                \"low\": \"低温 21℃\",\n" +
            "                \"date\": \"20日星期六\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"yesterday\": {\n" +
            "            \"fl\": \"微风\",\n" +
            "            \"fx\": \"南风\",\n" +
            "            \"high\": \"高温 28℃\",\n" +
            "            \"type\": \"晴\",\n" +
            "            \"low\": \"低温 15℃\",\n" +
            "            \"date\": \"15日星期一\"\n" +
            "        },\n" +
            "        \"aqi\": \"72\",\n" +
            "        \"city\": \"北京\"\n" +
            "    },\n" +
            "    \"message\": \"OK\"\n" +
            "}";*/
    private View mTestView;
    private RecyclerView recyclerView;
    private RecyclerWeatherAdapter recyclerWeatherAdapter;
    private ImageView ivNowInfo;
    private TextView tvNowInfo;
    private WeatherData weatherData;
    private ArrayList<String> data = new ArrayList<>();
    private ArrayList<Integer> imgData = new ArrayList<>();
    private List<WeatherData.DataBean.ForecastBean> forecast;
    private Handler handler;
    private String result;
    private static final int GET_WEB_SUCCESS = 1001;

    private TempratureView tempratureView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mTestView = inflater.inflate(R.layout.layout1, container, false);
        ivNowInfo = mTestView.findViewById(R.id.ivNowInfo);
        tvNowInfo = mTestView.findViewById(R.id.tvNowInfo);
        recyclerView = mTestView.findViewById(R.id.recycler_view);
//        Log.e("onCreateView:","hua");
        initHandle();
        getUseokHttp();
        tempratureView = mTestView.findViewById(R.id.tem_view);
//        setUseData();
        initData();
        return mTestView;
    }

    private void getUseokHttp() {
        String url = "https://www.sojson.com/open/api/weather/json.shtml?city=" + URLEncoder.encode("广州");
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("MainActivity",e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//        Log.e("msg:","json:"+response.body().string());
                Message message = Message.obtain();
                message.what = GET_WEB_SUCCESS;
                message.obj = response.body().string();
                handler.sendMessage(message);
            }
        });
    }

    private void initHandle() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what == GET_WEB_SUCCESS){
                    result = (String) message.obj;
//                    Log.e("initHandle:","hihi");
                    setUseData();
                }
                return false;
            }
        });
    }

    private void setUseData() {
        try {
            if(result!=null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm:ss
                //获取当前时间
                Date date = new Date(System.currentTimeMillis());
//                Log.e("msg","Date:"+simpleDateFormat.format(date));
                weatherData = new Gson().fromJson(result, WeatherData.class);
                forecast = weatherData.getData().getForecast();
                StringBuffer buffer = new StringBuffer();
                buffer.append("城市: ").append(weatherData.getCity());
                buffer.append("\n日期: ").append(simpleDateFormat.format(date));
                buffer.append("\n湿度: ").append(weatherData.getData().getShidu());
                buffer.append("\nPm25: ").append(weatherData.getData().getPm25());
                buffer.append("\n风向: ").append(forecast.get(0).getFx());
                buffer.append("\n天气状况: ").append(forecast.get(0).getType());
                buffer.append("\n温馨提示: ").append(forecast.get(0).getNotice());
    //        Log.e("msg","Data:"+buffer.toString());
                ivNowInfo.setImageResource(getWeatherImage(forecast.get(0).getType()));
                tvNowInfo.setText(buffer.toString());
                tempratureView.setData(forecast);

                Log.e("forecast:","msg:"+forecast);
//                int date = Integer.parseInt(forecast.get(0).getDate().substring(0, 2));
    //        Log.e("msg","Data:"+date);
    //            data = new ArrayList<>();
    //            imgData = new ArrayList<>();
                for (int i = 0; i < forecast.size(); i++) {
                    int wendu=(Integer.parseInt(forecast.get(i).getHigh().substring(3,5)) + Integer.parseInt(forecast.get(i).getLow().substring(3,5)))/2;
//                    Log.e("msg","Data:"+wendu);
                    StringBuffer buffer1 = new StringBuffer();
                    buffer1.append(forecast.get(i).getType());
                    buffer1.append("\n").append(forecast.get(i).getDate());
                    buffer1.append("\n平均温度: ").append(wendu).append("℃");
                    buffer1.append("\n").append(forecast.get(i).getFx());
    //            Log.e("msg","Data:"+buffer1);
                    data.add(buffer1.toString());
                    imgData.add(getWeatherImage(forecast.get(i).getType()));
                }
            }else {

                tvNowInfo.setText("无数据");
                String temp = "无数据";
                for (int i = 0; i < 5; i++) {
    //            Log.e("msg","Data:"+buffer1);
                    data.add(i+temp);
                    imgData.add(R.mipmap.ic_launcher);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Log.e("msg","Data:"+getWeatherImage(forecast.get(0).getType()));
        initData();
    }

    private void initData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity(),LinearLayoutManager.HORIZONTAL,false);
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        // 设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 设置adapter
        recyclerWeatherAdapter = new RecyclerWeatherAdapter(this.getActivity(),data,imgData);
        recyclerView.setAdapter(recyclerWeatherAdapter);
    }

  /*  private void initWeatherImg() {
        List<WeatherData.DataBean.ForecastBean> forecast = weatherData.getData().getForecast();

        ivWeather_a.setImageResource(getWeatherImage(forecast.get(0).getType()));
        ivWeather_b.setImageResource(getWeatherImage(forecast.get(1).getType()));
        ivWeather_c.setImageResource(getWeatherImage(forecast.get(2).getType()));
        ivWeather_d.setImageResource(getWeatherImage(forecast.get(3).getType()));
        ivWeather_e.setImageResource(getWeatherImage(forecast.get(4).getType()));
    }*/

    private int getWeatherImage(String type) {
        if(type.equals("晴")){
            return R.drawable.sun;
        }else if(type.equals("阵雨")){
            return R.drawable.thunderstorm;
        }else if(type.equals("中雨")){
            return R.drawable.rain;
        }else if(type.equals("小雨")){
            return R.drawable.rain;
        }else if(type.equals("大雨")){
            return R.drawable.rain;
        }else if(type.equals("雷阵雨")){
            return R.drawable.thunder;
        }else if(type.equals("多云")){
            return R.drawable.cloudy;
        }else if(type.equals("阴")){
            return R.drawable.overcast;
        }
        return R.drawable.sunny;
    }
}
